<?php
namespace services\models;

/**
 * Solr搜索接口
 *
 * @author huipeng.teng@liketry.com
 */
class SolrService {
    /**
     * 商品搜索和排序
     * @param int   $category   一级分类ID，值为1,2,3,4,5,6
     * @param string $goods_name 商品名称
     * @param int $brand_id 品牌ID
     * @param double $price_start RMB起始价格
     * @param double $price_end RMB结束价格
     * @param double $try_price_start 试豆起始价格
     * @param double $try_price_end 试豆结束价格
     * @param int $type 类型：0不限，1购买，2试用，3购买+试用
     * @param int $stock 1仅显示有货商品，0不限
     * @param int $sort_type 1热销，2价格，3试豆，4最新
     * @param string $sort ASC|DESC
     * @param int $page_num 第几页
     * @return array 返回[总数量, 商品列表, 品牌列表]
     */
    public function search($category = -1, $goods_name, $brand_id, $price_start = -1, $price_end = -1, $try_price_start = -1, $try_price_end = -1, 
            $type = 0, $stock = 0, $sort_type = 1, $sort = 'DESC', $page_num = 1, $page_size = 24) {
        $query = \Yii::$app->solr->createSelect();
        $helper = $query->getHelper();

        $category = intval($category);// 分类ID
        $brand_id = intval($brand_id);// 品牌ID
        $type = intval($type);// 1是购买，2是试用，3是购买+试用
        $stock = intval($stock);// 库存
        $sort_type = intval($sort_type);// 升序或降序
        $page_num = intval($page_num);// 页码

        // 筛选
        if($price_start === -1) {
            $price_start = '*';
        }
        if($price_end === -1) {
            $price_end = '*';
        }
        if($try_price_start === -1) {
            $try_price_start = '*';
        }
        if($try_price_end === -1) {
            $try_price_end = '*';
        }

        $condition = 'status:1 AND price:['.$price_start .' TO ' . $price_end.']';// RMB
        $condition .= ' AND try_price:[' . $try_price_start .' TO ' . $try_price_end.']';// 试豆
        if(!empty($goods_name)) {
            $condition .= ' AND goods_name:*' . preg_replace("/\s+/", '*', $helper->escapeTerm($goods_name)) . '*';//商品名称
        }
        if($brand_id > 0) {
            $condition .= ' AND brand_id:' . $brand_id;//品牌
        }
        if($type == 1) {
            $condition .= ' AND buy_status:1';
        } elseif($type == 2) {
            $condition .= ' AND try_status:1';
        } elseif($type == 3) {
            $condition .= ' AND buy_try_status:1';
        }
        if($stock === 1) {
            $condition .= ' AND stock:[1 TO *]';// 仅显示有库存的商品
        }
        if($category > -1) {
            $condition .= ' AND category:' . $category;
        }
        // 排序
        switch($sort_type) {
            case 2:
                $sort_field = 'price';// 价格
                break;
            case 3:
                $sort_field = 'try_price';// 试豆
                break;
            case 4:
                $sort_field = 'create_time';// 最新
                break;
            default:
                $sort_field = 'sale_num';// 销售数量
                break;
        }

        // 分页
        if($page_num < 1) {
            $page_num = 1;
        }
        $start = ($page_num - 1) * $page_size;

        // 查询
        $query->setQuery($condition);
        $query->setStart($start)->setRows($page_size);
        $query->setFields(array('id'));
        $query->addSort($sort_field, ($sort === 'ASC' ? $query::SORT_ASC : $query::SORT_DESC));
        if($sort_field !== 'create_time') {
            $query->addSort('create_time', $query::SORT_ASC);
        }
        $result_set = \Yii::$app->solr->select($query);

        $total_num = $result_set->getNumFound();
        if($total_num < 1) {
            return ['total_num' => 0, 'goods_list' => [], 'brand_list' => []];
        }

        $goods_list = [];
        foreach(\yii\helpers\ArrayHelper::toArray($result_set) as $row) {
            $goods_list[] = intval($row['id']);
        }

        $brand_list = $this->getBrandList($condition);

        return ['total_num' => $total_num, 'goods_list' => $goods_list, 'brand_list' => $brand_list];
    }
    //微信端列表页搜索

    /**
     * wap端商品搜索和排序
     * @param int $sort_type 1热销，2价格，3试豆，4最新
     * @param string $sort ASC|DESC
     * @param int $page_num 第几页
     * @param int $category 1换新颜，2尝美味，3黑科技 4寻尖货 5趣好店 6 爱北鼻
     * @return array 返回[总数量, 商品列表, 品牌列表]
     */
    public function WapSearch($sort_type = 1, $sort = 'DESC', $page_num = 1, $category = -1) {
        $query = \Yii::$app->solr->createSelect();
        $helper = $query->getHelper();
        $condition = 'status:1 AND ';
        if($category > -1) {
            $condition .= 'category:'.$category;
        }
        // 排序
        switch($sort_type) {
            case 2:
                $sort_field = 'price';// 价格
                break;
            case 3:
                $sort_field = 'try_price';// 试豆
                break;
            case 4:
                $sort_field = 'create_time';// 最新
                break;
            default:
                $sort_field = 'sale_num';// 销售数量
                break;
        }
        // 分页
        if($page_num < 1) {
            $page_num = 1;
        }
        $page_size = 10;
        $start = ($page_num - 1) * $page_size;
        // 查询
        $query->setQuery($condition);
        $query->setStart($start)->setRows($page_size);
        $query->setFields(array('id'));
        $query->addSort($sort_field, ($sort === 'ASC' ? $query::SORT_ASC : $query::SORT_DESC));
        if($sort_field !== 'create_time') {
            $query->addSort('create_time', $query::SORT_ASC);
        }
        $result_set = \Yii::$app->solr->select($query);
        $total_num = $result_set->getNumFound();
        if($total_num < 1) {
            return ['total_num' => 0, 'goods_list' => []];
        }
        $goods_list = [];
        foreach(\yii\helpers\ArrayHelper::toArray($result_set) as $row) {
            $goods_list[] = intval($row['id']);
        }

        //$brand_list = $this->getBrandList($condition);

        return ['total_num' => $total_num, 'goods_list' => $goods_list];
    }

    /**
     * 通过搜索条件获取品牌信息
     * @param string $condition 搜索条件
     * @return array 品牌列表
     */
    public function getBrandList($condition) {
        $query = \Yii::$app->solr->createSelect();
        $query->setQuery($condition);
        $query->setStart(0)->setRows(100000);
        $query->setFields(array('brand_id', 'brand_index', 'brand_name'));

        $groupComponent = $query->getGrouping();
        $groupComponent->addField('brand_id');
        $groupComponent->setLimit(1);
//        $groupComponent->setNumberOfGroups(false);

        $result_set = \Yii::$app->solr->select($query);
        $groups = $result_set->getGrouping();
        $brand_array = \yii\helpers\ArrayHelper::toArray($groups);

        if(!isset($brand_array) || empty($brand_array['brand_id'])) {
            return [];
        }

        $return_array = [];
        foreach($brand_array['brand_id'] as $row) {
            if($row[0]['brand_id'] > 0) {
                $temp_array = [];
                $temp_array['brand_name'] = isset($row[0]['brand_name']) ? $row[0]['brand_name'] : '';
                $temp_array['brand_id'] = $row[0]['brand_id'];
                $return_array[strtoupper($row[0]['brand_index'])][] = $temp_array;
            }
        }

        return $return_array;
    }

    /**
     * 定时批量更新商品索引
     */
    public function updateGoodsIndex($count = 1000) {
        $i = 0;
        $document_list = [];

        $solr_goods_rows = \services\models\SolrGoods::findGoods($count);
        if(empty($solr_goods_rows)) {
            return false;
        }

        foreach($solr_goods_rows as $row) {
            $tmpArray = [];
            $tmpArray['id'] = $row['goods_id'];
            $tmpArray['brand_id'] = $row['brand_id'];
            $tmpArray['brand_index'] = $row['brand_index'];
            $tmpArray['brand_name'] = $row['brand_name'];
            $tmpArray['create_time'] = $row['create_time'];
            $tmpArray['goods_name'] = $row['goods_name'];            
            $tmpArray['price'] = $row['price'];
            $tmpArray['try_price'] = $row['try_price'];
            $tmpArray['buy_status'] = $row['buy_status'];
            $tmpArray['try_status'] = $row['try_status'];
            $tmpArray['buy_try_status'] = $row['buy_try_status'];
            $tmpArray['sale_num'] = $row['sale_num'];
            $tmpArray['stock'] = $row['stock'];
            $tmpArray['status'] = $row['status'];

            foreach(\Yii::$app->params['category_list'] as $category_key => $category_row) {
                if(in_array($row['category_1'], $category_row['childs'])) {
                    $tmpArray['category'] = $category_key;
                    break;
                }
            }

            $document_list[] = $tmpArray;
            ++$i;

            if($i == 100) {
                $this->updateBatch($document_list);
                $document_list = [];
                $i = 0;
            }

            // 添加完索引，从solr_goods表移除商品。
            SolrGoods::deleteAll('goods_id=' . $row['goods_id']);
        }
        unset($solr_goods_rows);

        if(!empty($document_list)) {
            $this->updateBatch($document_list);
        }
        unset($document_list);
    }

    /**
     * 批量更新商品索引
     */
    public function updateBatch($dataList) {
        if(empty($dataList)) {
            return false;
        }

        $document_list = [];
        $update = \Yii::$app->solr->createUpdate();

        foreach($dataList as $row) {
            $document = $update->createDocument();
            foreach($row as $key => $value) {
                $document->$key = $value;
            }
            $document_list[] = $document;
        }

        $update->addDocuments($document_list);
        $update->addCommit();
        \Yii::$app->solr->update($update);
    }

    /**
     * 更新单个商品索引
     * @param array $dataArray 商品属性组成的一维数组
     * @return int
     */
    public function update($dataArray) {
        $update = \Yii::$app->solr->createUpdate();
        $document = $update->createDocument();

        foreach($dataArray as $key => $value) {
            $document->$key = $value;
        }

        $update->addDocument($document);
        $update->addCommit();
        $result = \Yii::$app->solr->update($update);
        return $result->getStatus();
    }

        /**
     * 通过商品ID删除索引
     * @param int $goods_id 商品ID
     * @return int
     */
    public function deleteById($goods_id) {
        $update = \Yii::$app->solr->createUpdate();
        $update->addDeleteById($goods_id);
        $update->addCommit();
        $result = \Yii::$app->solr->update($update);
        return $result->getStatus();
    }

    /**
     * 通过查询语句删除索引
     * @param string $condition 查询条件
     * @return int
     */
    public function deleteByQuery($condition) {
        $update = \Yii::$app->solr->createUpdate();
        $update->addDeleteQuery($condition);
        $update->addCommit();
        $result = \Yii::$app->solr->update($update);
        return $result->getStatus();
    }

        /**
     * 优化索引
     * @return int
     */
    public function optimize() {
        $update = \Yii::$app->solr->createUpdate();
        $update->addOptimize(true, false, 5);
        $result = \Yii::$app->solr->update($update);
        return $result->getStatus();
    }

    public function ping() {
        $ping = \Yii::$app->solr->createPing();
        $result = \Yii::$app->solr->ping($ping)->getData();

        if(isset($result['status']) && $result['status'] === 'OK') {
            return true;
        }

        return false;
    }
}